<template>
  <div class="role-management">
    <div class="page-header">
      <h2>角色管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增角色
      </el-button>
    </div>

    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userCount" label="用户数量" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button size="small" @click="handlePermission(row)">
              <el-icon><Key /></el-icon>
              权限
            </el-button>
            <el-button size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" :disabled="row.code === 'admin'">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 角色编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="权限配置" width="800px">
      <div class="permission-container">
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTree"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          :default-expand-all="true"
        />
      </div>
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePermissionSubmit" :loading="permissionSubmitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, Key } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const submitting = ref(false)
const roleFormRef = ref()

// 权限对话框
const permissionDialogVisible = ref(false)
const permissionSubmitting = ref(false)
const permissionTreeRef = ref()
const currentRole = ref(null)
const checkedPermissions = ref([])

// 角色表单
const roleForm = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  status: 'active'
})

// 表单验证规则
const roleRules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }]
}

// 权限树配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 权限树数据
const permissionTree = ref([
  {
    id: 'user',
    name: '用户管理',
    children: [
      { id: 'user:list', name: '用户列表' },
      { id: 'user:add', name: '新增用户' },
      { id: 'user:edit', name: '编辑用户' },
      { id: 'user:delete', name: '删除用户' },
      { id: 'role:list', name: '角色列表' },
      { id: 'role:add', name: '新增角色' },
      { id: 'role:edit', name: '编辑角色' },
      { id: 'role:delete', name: '删除角色' }
    ]
  },
  {
    id: 'hr',
    name: '人力资源',
    children: [
      { id: 'employee:list', name: '员工档案' },
      { id: 'attendance:list', name: '考勤管理' },
      { id: 'salary:list', name: '薪资管理' }
    ]
  },
  {
    id: 'purchase',
    name: '采购管理',
    children: [
      { id: 'supplier:list', name: '供应商管理' },
      { id: 'purchase:order', name: '采购订单' },
      { id: 'purchase:in', name: '采购入库' }
    ]
  },
  {
    id: 'warehouse',
    name: '仓库管理',
    children: [
      { id: 'inventory:list', name: '库存查询' },
      { id: 'warehouse:in', name: '入库管理' },
      { id: 'warehouse:out', name: '出库管理' },
      { id: 'inventory:check', name: '盘点管理' }
    ]
  },
  {
    id: 'sales',
    name: '销售管理',
    children: [
      { id: 'customer:list', name: '客户管理' },
      { id: 'sales:order', name: '销售订单' },
      { id: 'cashier:manage', name: '收银管理' }
    ]
  },
  {
    id: 'finance',
    name: '财务管理',
    children: [
      { id: 'account:list', name: '会计科目' },
      { id: 'voucher:list', name: '凭证管理' },
      { id: 'finance:report', name: '财务报表' }
    ]
  },
  {
    id: 'basic',
    name: '基础档案',
    children: [
      { id: 'product:list', name: '商品档案' },
      { id: 'bom:list', name: 'BOM管理' }
    ]
  },
  {
    id: 'report',
    name: '报表中心',
    children: [
      { id: 'report:standard', name: '标准报表' },
      { id: 'report:custom', name: '自定义报表' }
    ]
  },
  {
    id: 'analysis',
    name: '分析中心',
    children: [
      { id: 'pivot:analysis', name: '透视分析' },
      { id: 'ai:analysis', name: 'AI分析' }
    ]
  },
  {
    id: 'lowcode',
    name: '低代码开发',
    children: [
      { id: 'form:designer', name: '表单设计器' },
      { id: 'flow:designer', name: '流程设计器' }
    ]
  },
  {
    id: 'system',
    name: '系统管理',
    children: [
      { id: 'system:config', name: '系统配置' },
      { id: 'system:monitor', name: '系统监控' },
      { id: 'data:model', name: '数据模型' }
    ]
  }
])

// 获取角色列表
const getRoleList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        name: '系统管理员',
        code: 'admin',
        description: '系统最高权限管理员',
        status: 'active',
        userCount: 1,
        createTime: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        name: '企业管理员',
        code: 'enterprise_admin',
        description: '企业级管理员，拥有企业内所有权限',
        status: 'active',
        userCount: 2,
        createTime: '2024-01-02 10:00:00'
      },
      {
        id: 3,
        name: '部门经理',
        code: 'department_manager',
        description: '部门管理权限',
        status: 'active',
        userCount: 5,
        createTime: '2024-01-03 10:00:00'
      },
      {
        id: 4,
        name: '业务员工',
        code: 'employee',
        description: '普通业务员工权限',
        status: 'active',
        userCount: 20,
        createTime: '2024-01-04 10:00:00'
      },
      {
        id: 5,
        name: '财务人员',
        code: 'finance',
        description: '财务相关权限',
        status: 'active',
        userCount: 3,
        createTime: '2024-01-05 10:00:00'
      },
      {
        id: 6,
        name: '仓库管理员',
        code: 'warehouse_manager',
        description: '仓库管理相关权限',
        status: 'active',
        userCount: 4,
        createTime: '2024-01-06 10:00:00'
      }
    ]
    
    tableData.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getRoleList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: ''
  })
  handleSearch()
}

// 新增角色
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增角色'
  Object.assign(roleForm, {
    id: null,
    name: '',
    code: '',
    description: '',
    status: 'active'
  })
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑角色'
  Object.assign(roleForm, { ...row })
  dialogVisible.value = true
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('删除成功')
    getRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 权限配置
const handlePermission = (row) => {
  currentRole.value = row
  // 模拟获取角色权限
  const mockPermissions = {
    admin: ['user', 'user:list', 'user:add', 'user:edit', 'user:delete', 'role:list', 'role:add', 'role:edit', 'role:delete', 'hr', 'employee:list', 'attendance:list', 'salary:list'],
    enterprise_admin: ['user', 'user:list', 'user:add', 'user:edit', 'hr', 'employee:list', 'attendance:list'],
    department_manager: ['hr', 'employee:list', 'attendance:list'],
    employee: ['hr', 'employee:list'],
    finance: ['finance', 'account:list', 'voucher:list', 'finance:report'],
    warehouse_manager: ['warehouse', 'inventory:list', 'warehouse:in', 'warehouse:out', 'inventory:check']
  }
  
  checkedPermissions.value = mockPermissions[row.code] || []
  permissionDialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    await roleFormRef.value.validate()
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    dialogVisible.value = false
    getRoleList()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

// 提交权限配置
const handlePermissionSubmit = async () => {
  try {
    permissionSubmitting.value = true
    
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('权限配置成功')
    permissionDialogVisible.value = false
  } catch (error) {
    ElMessage.error('权限配置失败')
  } finally {
    permissionSubmitting.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  getRoleList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  getRoleList()
}

// 组件挂载时获取数据
onMounted(() => {
  getRoleList()
})
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-form {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  background: #fafafa;
}

.permission-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}
</style>